<template>
  <view class="restaurant-page">
    <!-- 页面标题和添加按钮 -->
    <u-button class="add-btn" type="primary" @click="showAddForm = true"><u-icon name="plus" size="25" color="#fff"></u-icon></u-button>

    <!-- 筛选区域 -->
    <view class="filter-area">
      <u-tabs :list="categoryTabs" @click="onCategoryChange" :current="currentCategory"></u-tabs>
    </view>

    <!-- 餐厅列表 -->
    <view class="restaurant-list">
      <view v-if="loading" class="loading">
        <u-loading-icon mode="spinner"></u-loading-icon>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="filteredRestaurants.length === 0" class="empty">
        <u-empty mode="data" text="暂无餐厅数据">
          <template #button>
            <u-button type="primary" size="normal" @click="showAddForm = true">添加第一个餐厅</u-button>
          </template>
        </u-empty>
      </view>
      
      <view v-else>
        <view
          v-for="restaurant in filteredRestaurants"
          :key="restaurant.id"
          class="restaurant-item"
          @click="editRestaurant(restaurant)"
        >
          <view class="restaurant-info">
            <text class="restaurant-name">{{ restaurant.name }}</text>
            <view class="tags">
              <u-tag :text="restaurant.category" type="success" size="mini"></u-tag>
              <u-tag :text="getFrequencyText(restaurant.frequency_rule)" type="info" size="mini"></u-tag>
            </view>
            <text v-if="restaurant.notes" class="notes">{{ restaurant.notes }}</text>
          </view>
          <view class="restaurant-actions" @click.stop>
            <u-icon 
              name="trash" 
              size="18" 
              color="#f56c6c" 
              @click="deleteRestaurant(restaurant)"
              class="delete-icon"
            ></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加/编辑餐厅弹窗 -->
    <u-popup :show="showAddForm" @close="closeForm" mode="bottom" border-radius="20">
      <view class="form-popup">
        <view class="form-header">
          <text class="form-title">{{ isEditing ? '编辑餐厅' : '添加餐厅' }}</text>
          <u-icon name="close" size="20" @click="closeForm"></u-icon>
        </view>
        
        <view class="form-content">
          <u-form :model="formData" ref="formRef" :rules="formRules" label-width="75">
            <u-form-item label="餐厅名称" prop="name" required>
              <u-input v-model="formData.name" placeholder="请输入餐厅名称"></u-input>
            </u-form-item>
            
            <u-form-item label="餐厅分类" prop="category" required>
              <u-radio-group v-model="formData.category" placement="row">
                <u-radio
                  v-for="cat in categories"
                  :key="cat.value"
                  :name="cat.value"
                  :label="cat.label"
                ></u-radio>
              </u-radio-group>
            </u-form-item>
            
            <u-form-item label="频率规则" prop="frequency_rule" required>
              <u-radio-group v-model="formData.frequency_rule" placement="column">
                <u-radio name="daily" label="每天可选"></u-radio>
                <u-radio name="weekly" label="每周限一次"></u-radio>
                <u-radio name="monthly" label="每月限一次"></u-radio>
              </u-radio-group>
            </u-form-item>
            
            <u-form-item label="备注" prop="notes">
              <u-textarea v-model="formData.notes" placeholder="请输入备注信息（可选）" maxlength="200"></u-textarea>
            </u-form-item>
          </u-form>
        </view>
        
        <view class="form-actions">
          <u-button type="default" @click="closeForm">取消</u-button>
          <u-button type="primary" @click="submitForm" :loading="submitting">{{ isEditing ? '更新' : '添加' }}</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 删除确认弹窗 -->
    <u-modal :show="showDeleteModal" @close="showDeleteModal = false" :showCancelButton="true" title="确认删除" content="确定要删除这个餐厅吗？删除后无法恢复。" @cancel="showDeleteModal = false" @confirm="confirmDelete">
      <!-- <template #confirmButton>
        <u-button type="error" @click="confirmDelete" :loading="deleting">删除</u-button>
      </template> -->
    </u-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { api } from '../../api'
import type { Restaurant } from '../../api/types'

// 响应式数据
const loading = ref(false)
const restaurants = ref<Restaurant[]>([])
const showAddForm = ref(false)
const isEditing = ref(false)
const editingId = ref<string | null>(null)
const submitting = ref(false)
const showDeleteModal = ref(false)
const deletingRestaurant = ref<Restaurant | null>(null)
const deleting = ref(false)
const currentCategory = ref(0)
const formRef = ref()

// 表单数据
const formData = ref<{
  name: string
  category: string
  frequency_rule: 'daily' | 'weekly' | 'monthly'
  notes: string
}>({
  name: '',
  category: '',
  frequency_rule: 'daily',
  notes: ''
})

// 分类选项
const categories = [
  { label: '米饭', value: '米饭' },
  { label: '面条', value: '面条' },
  { label: '米线', value: '米线' },
  { label: '米粉', value: '米粉' },
  { label: '汉堡', value: '汉堡' },
  { label: '饺子', value: '饺子' },
  { label: '其他', value: '其他' }
]

// 分类标签
const categoryTabs = computed(() => {
  const allTab = { name: '全部' }
  const categoryTabs = categories.map(cat => ({ name: cat.label }))
  return [allTab, ...categoryTabs]
})

// 筛选后的餐厅列表
const filteredRestaurants = computed(() => {
  if (currentCategory.value === 0) {
    return restaurants.value
  }
  const selectedCategory = categories[currentCategory.value - 1]?.label
  return restaurants.value.filter(r => r.category === selectedCategory)
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入餐厅名称', trigger: 'blur' },
    { min: 1, max: 50, message: '餐厅名称长度在1到50个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择餐厅分类', trigger: 'change' }
  ],
  frequency_rule: [
    { required: true, message: '请选择频率规则', trigger: 'change' }
  ]
}

// 获取频率文本
const getFrequencyText = (rule: string) => {
  const map: Record<string, string> = {
    daily: '每天可选',
    weekly: '每周限一次',
    monthly: '每月限一次'
  }
  return map[rule] || rule
}



// 加载餐厅列表
const loadRestaurants = async () => {
  loading.value = true
  try {
    const response = await api.restaurant.getAllRestaurants()
    restaurants.value = response?.data || []
  } catch (error) {
    console.error('加载餐厅列表失败:', error)
    // 错误处理已在request.ts中统一处理
  } finally {
    loading.value = false
  }
}

// 分类切换
const onCategoryChange = (item: any, index: number) => {
  currentCategory.value = index
}

// 编辑餐厅
const editRestaurant = (restaurant: Restaurant) => {
  isEditing.value = true
  editingId.value = restaurant.id
  formData.value = {
    name: restaurant.name,
    category: restaurant.category,
    frequency_rule: restaurant.frequency_rule,
    notes: restaurant.notes || ''
  }
  showAddForm.value = true
}

// 删除餐厅
const deleteRestaurant = (restaurant: Restaurant) => {
  deletingRestaurant.value = restaurant
  showDeleteModal.value = true
}

// 关闭表单
const closeForm = () => {
  showAddForm.value = false
  isEditing.value = false
  editingId.value = null
  
  // 重置表单数据
  formData.value = {
    name: '',
    category: '',
    frequency_rule: 'daily',
    notes: ''
  }
  
  // 清除表单验证状态
  formRef.value?.clearValidate()
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  try {
    await formRef.value?.validate()
  } catch (error) {
    console.log('表单验证失败:', error)
    return
  }
  
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入餐厅名称',
      icon: 'error'
    })
    return
  }
  
  if (!formData.value.category) {
    uni.showToast({
      title: '请选择餐厅分类',
      icon: 'error'
    })
    return
  }
  
  submitting.value = true
  try {
    if (isEditing.value && editingId.value) {
      // 更新餐厅
      await api.restaurant.updateRestaurant(editingId.value, {
        name: formData.value.name.trim(),
        category: formData.value.category,
        frequencyRule: formData.value.frequency_rule,
        notes: formData.value.notes.trim() || undefined
      })
      
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
    } else {
      // 添加餐厅
      await api.restaurant.createRestaurant({
        name: formData.value.name.trim(),
        category: formData.value.category,
        frequencyRule: formData.value.frequency_rule,
        notes: formData.value.notes.trim() || undefined
      })
      
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
    }
    
    closeForm()
    await loadRestaurants()
  } catch (error) {
    console.error('提交失败:', error)
    // 错误处理已在request.ts中统一处理
  } finally {
    submitting.value = false
  }
}

// 确认删除
const confirmDelete = async () => {
  if (!deletingRestaurant.value) return
  
  deleting.value = true
  try {
    await api.restaurant.deleteRestaurant(deletingRestaurant.value.id)
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
    
    showDeleteModal.value = false
    deletingRestaurant.value = null
    await loadRestaurants()
  } catch (error) {
    console.error('删除失败:', error)
    // 错误处理已在request.ts中统一处理
  } finally {
    deleting.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadRestaurants()
})
</script>

<style scoped>
.restaurant-page {
  min-height: calc(100vh - 50px);
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #ebeef5;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #303133;
}

.add-btn {
  width: 60px;
    height: 60px;
    position: fixed;
    bottom: 80px;
    right: 30px;
    border-radius: 100%;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.filter-area {
  position: sticky;
  z-index: 1;
  top: 0px;
  background-color: #ffffff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #ebeef5;
}

/* 强制u-tabs组件横向显示 */
.filter-area :deep(.u-tabs) {
  width: 100%;
  display: flex;
  flex-direction: row;
  overflow-x: auto;
  overflow-y: hidden;
}

.filter-area :deep(.u-tabs__wrapper) {
  display: flex;
  flex-direction: row;
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
}

.filter-area :deep(.u-tabs__wrapper__nav) {
  display: flex;
  flex-direction: row;
  width: auto;
  min-width: 100%;
}

.filter-area :deep(.u-tabs__wrapper__nav__item) {
  flex-shrink: 0;
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.restaurant-list {
  padding: 20rpx 30rpx;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 20rpx;
}

.empty {
  padding: 100rpx 0;
}

.restaurant-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.restaurant-info {
  flex: 1;
}

.restaurant-actions {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
}

.delete-icon {
  padding: 10rpx;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.delete-icon:hover {
  background-color: rgba(245, 108, 108, 0.1);
}

.restaurant-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #303133;
  display: block;
  margin-bottom: 16rpx;
}

.tags {
  display: flex;
  gap: 16rpx;
  margin-bottom: 12rpx;
}

.notes {
  font-size: 26rpx;
  color: #909399;
  display: block;
}

.form-popup {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 90vh;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #ebeef5;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #303133;
}

.form-content {
  padding: 30rpx;
  max-height: calc(100% - 200px);
  overflow-y: auto;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #ebeef5;
}

.form-actions .u-button {
  /* flex: 1;  */
}
</style>